package com.yutianran.ezadapter.vg;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.yutianran.ezadapter.CommonViewHolder;
import com.yutianran.ezadapter.LayoutHolder;
import com.yutianran.ezadapter.LayoutPlayer;
import com.yutianran.ezadapter.TypeHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VgHelper {

    private List<?> list;
    private ViewGroup containerView;
    private Map<Integer, LayoutPlayer<?>> playerMap;//layoutId --> player
    private Map<Class, Integer> layoutIdMap;//Class --> layoutId
    private List<Integer> layoutIds;// viewType --> layoutId

    public VgHelper() {
        playerMap = new HashMap<>();
        layoutIdMap = new HashMap<>();
        layoutIds = new ArrayList<>();
    }

    public VgHelper(List<?> list) {
        this.list = list;
        playerMap = new HashMap<>();
        layoutIdMap = new HashMap<>();
        layoutIds = new ArrayList<>();
    }

    public static VgHelper create() {
        return new VgHelper();
    }

    public static VgHelper with(List<?> list) {
        return new VgHelper(list);
    }

    public <T> VgHelper register(LayoutHolder<T> holder) {
        return register(holder.getLayoutId(), holder);
    }

    public <T> VgHelper register(int layoutId, LayoutPlayer<T> player) {
        playerMap.put(layoutId, player);
        layoutIdMap.put(TypeHelper.getActualTypeArguments(player), layoutId);
        layoutIds.add(layoutId);
        return this;
    }

    public void setData(List<?> list) {
        this.list = list;
        refresh();
    }

    public void into(ViewGroup containerView) {
        this.containerView = containerView;
        refresh();
    }

    private void refresh() {
        if (list == null) {
            throw new RuntimeException("请设置数据源");
        }
        if (containerView == null) {
            throw new RuntimeException("请设置父视图");
        }
        containerView.removeAllViews();
        //遍历数据源,根据数据的Class类型，找到不同的布局
        for (int i = 0; i < list.size(); i++) {
            Object obj = list.get(i);
            Class clazz = obj.getClass();
            int layoutId = layoutIdMap.get(clazz);
            View itemView = LayoutInflater.from(containerView.getContext()).inflate(layoutId, containerView, false);
            containerView.addView(itemView);
            LayoutPlayer<?> player = playerMap.get(layoutId);
            convert(player, obj, new CommonViewHolder(itemView));
        }
    }

    private <T> void convert(LayoutPlayer<T> player, Object obj, CommonViewHolder holder) {
        T t = (T) obj;
        player.bindData(t, holder);
    }
}
